package etnorservice.etnor_service.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 生成6位数字验证码
    public String generateCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000); // 生成100000-999999之间的随机数
        return String.valueOf(code);
    }

    // 发送验证码邮件
    public void sendVerificationCode(String email) throws MessagingException {
        // 生成验证码
        String code = generateCode();

        // 保存验证码到Redis，有效期10分钟
        redisTemplate.opsForValue().set("verification:code:" + email, code, 10, TimeUnit.MINUTES);

        // 创建邮件正文
        Context context = new Context();
        context.setVariable("code", code);
        String content = templateEngine.process("mail/verification-code", context);

        // 发送邮件
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom("support@etnor.xyz");
        helper.setTo(email);
        helper.setSubject("E特尔诺 - 注册验证码");
        helper.setText(content, true);

        mailSender.send(message);
    }

    // 验证验证码
    public boolean verifyCode(String email, String code) {
        String storedCode = redisTemplate.opsForValue().get("verification:code:" + email);
        return storedCode != null && storedCode.equals(code);
    }
}